# from wo.goeasy import test_go
from flask import Blueprint, jsonify, request

from models.entity.project import Project
from models.entity.project_item import Project_Item
import json
from datetime import datetime

import requests
import json

from models.entity.projectitem_with_sensor import ProjectItemWithSensor
from utils.result import result

mod = Blueprint("project_item", __name__, url_prefix="/core/project_item", template_folder="templates",
                static_folder="static")


@mod.route('/get_all/', methods=['GET', 'POST'])
def task_index():
    """获取全部项目应用"""
    tmp = {}
    data = []
    project_items = Project_Item.query.all()
    for item in project_items:
        data.append(item.to_dict())
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = data
    return jsonify(tmp)


@mod.route('/add/', methods=['GET', 'POST'])
def add_project_item():
    """增加应用"""
    """
    {
    "name":"ddddd",
    "project_id":"ddddd",
    "type":"ddddd",
    }
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
            name = data['name']
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)
        if Project_Item().get_project_item_by_name(name):
            return result(success=0, error_code=-1, error_msg="名称已存在")

        project_item = Project_Item()
        try:
            project_item.from_dict(data)
        except RuntimeError as e:
            return result(success=0,error_code=-1,error_msg=e)
        if project_item.save() is False:
            return result(success=0,error_code=-4,error_msg="保存错误")
        else:
            return result(success=1,error_code=None,error_msg=None)


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_project_item():
    """编辑项目应用"""
    """
        {
        "id":1,
        "name":"项目2",
        "type": 12

    }

    """
    if request.method == 'POST':
        try:
            dict = json.loads(request.data.decode("utf-8"))
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)
        tmp = {}
        data = []
        if "name" not in dict:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "名称不能为空"
            tmp['data'] = data
            return jsonify(tmp)
        name = dict['name']
        type = dict['type']
        project_item = Project_Item.query.filter_by(id=dict['id']).first()
        if project_item.name != name and Project_Item().get_project_item_by_name(name):
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "名称已经存在"
            tmp['data'] = data
            return jsonify(tmp)
        project_item.name = name
        if project_item.name != name and Project_Item().get_project_item_by_type(type):
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "类型已经存在"
            tmp['data'] = data
            return jsonify(tmp)
        project_item.type = type
        if project_item.save():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -3
            tmp['error_msg'] = "unknown error"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/del/', methods=['GET', 'POST'])
def del_project_item():
    """删除项目应用"""
    """
    {
    "id":1
    }
    """
    tmp = {}
    data = []
    dict = json.loads(request.data.decode("utf-8"))
    id = dict['id']
    project_item = Project_Item.query.filter_by(id=id).first()
    if not project_item:
        tmp['success'] = 0
        tmp['error_code'] = -1
        tmp['error_msg'] = "当前记录不存在，请重新选择"
        tmp['data'] = data
        return jsonify(tmp)
    if project_item.delete():
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        tmp['success'] = 0
        tmp['error_code'] = -2
        tmp['error_msg'] = "未知错误"
        tmp['data'] = data
        return jsonify(tmp)

@mod.route("/get_project_item_by_project_id/", methods=["GET", "POST"])
def get_project_item_by_project_id():
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)
        project_id = data['project_id']
        res = Project_Item().get_project_item_by_project_id(project_id)

        return result(success=1, data=res)

@mod.route("/get_sensors_by_project_item_id/", methods=["GET", "POST"])
def get_sensors_by_project_item_id():
    """
    {"project_item_id":1}
    :return: [sensors:[1,2,3....]]
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)
        project_item_id = data['project_item_id']
        print(1111)
        connectors = ProjectItemWithSensor.query.filter_by(project_item_id=project_item_id).all()
        sensor_list = []
        for item in connectors:
            sensor_list.append(item.sensor_id)
        # print('connectors', connectors)
        # print('connectors长度', len(connectors))
        print(2222)
        return result(success=1, data=sensor_list)


@mod.route("/update_sensor_to_project_item/", methods=["GET", "POST"])
def update_sensor_to_project_item():
    """
        {
        "project_item_id":1
        "sensors" [1,3 ...]
        }
        """
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
        except:
            error_msg = {
                "success": 0,
                "error_code": -1,
                "error_msg": "json格式错误"
            }
            return jsonify(error_msg)
        project_item_id = data['project_item_id']
        sensor_ids = data['sensors']
        connectors = ProjectItemWithSensor.query.filter_by(project_item_id=project_item_id).all()

        # connectors = RoleWithButton.query.filter_by(role_id=role_id).all()
        # print(len(connectors), type(connectors))
        # print('connectors', connectors)
        # print(111111)
        for item in connectors:
            # print(222,item) ,加上这个就报错 'ProjectItemWithSensor' object has no attribute 'project_id',有时间研究
            if item.delete() != 0:
                return jsonify('删除错误')
        print('删除成功')
        print(3333)
        ProjectItemWithSensor.add_sensors_to_project_item(project_item_id, sensor_ids)
        return result(data=[])
